using System.Collections.Generic;
using BSDS.Core.Data.Local;
using BSDS.Core.Model;
using BSDS.Core.Model.Data;

namespace BSDS.Core.Data
{
    public class SerializationUtils
    {
        private const string Amp = "&amp;";
        private const string Lt = "&lt;";
        private const string Gt = "&gt;";
        private const string Apos = "&apos;";

        public string EscapeSpecialCharacters(string text)
        {
            var ampersandIndices = new List<int>();
            var ampersandIndex = text.IndexOf('&', 0);

            while (ampersandIndex != -1)
            {
                var suffix = text.Substring(ampersandIndex, text.Length - ampersandIndex);

                if (!suffix.StartsWith(Amp) && !suffix.StartsWith(Lt) &&
                    !suffix.StartsWith(Gt) && !suffix.StartsWith(Apos))
                {
                    ampersandIndices.Add(ampersandIndex);
                }

                ampersandIndex = text.IndexOf('&', ampersandIndex+1);
            }

            for (int i = ampersandIndices.Count-1; i >= 0; i--)
            {
                var currentIndex = ampersandIndices[i];
                var prefix = text.Substring(0, currentIndex);
                var suffix = text.Substring(currentIndex + 1, text.Length - currentIndex - 1);

                text = prefix + Amp + suffix;
            }


            text = text.Replace("<", Lt);
            text = text.Replace(">", Gt);
            text = text.Replace("'", Apos);

            return text;
        }

        public string GetValue(AttributeValue value, SerializationOptions options)
        {
            if (options == SerializationOptions.SerializeForUpload)
            {
                if (value.AttributeInfo.Datatype.ToLower() == "boolean")
                {
                    switch (value.Value)
                    {
                        case "0":
                        case "N":
                            return "false";
                        case "1":
                        case "Y":
                            return "true";
                        default:
                            return value.Value;
                    }
                }

                if (value.AttributeInfo.Name.ToLower() == "longitude" && string.IsNullOrEmpty(value.Value))
                {
                    return "0.0";
                }

                if (value.AttributeInfo.Name.ToLower() == "latitude" && string.IsNullOrEmpty(value.Value))
                {
                    return "0.0";
                }
            }

            return value.Value;
        }
    }
}
